package com.CityHunter.Activity;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.CityHunter.R;
import com.CityHunter.Adapter.BuddyAdapter;
import com.CityHunter.DataObject.Buddy;
import com.CityHunter.DataObject.Group;
import com.CityHunter.MapActivity.CreateSchedulePage;
import com.CityHunter.Request.AddBuddyRequest;
import com.CityHunter.Request.CreateGroupRequest;
import com.CityHunter.Request.DeleteBuddyRequest;
import com.CityHunter.Request.GetBuddyIdRequest;
import com.CityHunter.Request.GetBuddyRequest;
import com.CityHunter.Request.GetGroupRequest;
import com.CityHunter.Request.InviteGroupRequest;
import com.CityHunter.Request.UpdateStateRequest;
import com.CityHunter.Service.UpdateLocationService;

public class BuddyPage extends Activity {

	private ListView bdyp_lv_buddyList;
	private EditText abdy_et_email, cgrp_et_title, cgrp_et_description;

	private SharedPreferences sp;
	private int userid;
	private Buddy selectedBuddy;
	private Group selectedGroup;
	private List<Buddy> buddies;
	private List<Group> groups;

	// Declare Handler and Runnable object
	private Handler objHandler = new Handler();

	private Runnable loopUpdateList = new Runnable() {
		public void run() {
			updateBuddyList();
			objHandler.postDelayed(loopUpdateList, 15000);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.bdyp);
		sp = getSharedPreferences("cityhunter", 0);

		// Mapping ListView
		bdyp_lv_buddyList = (ListView) findViewById(R.id.bdyp_lv_buddyList);

		// Get userid from sharepreference
		userid = sp.getInt("userid", 0);

		getGroupList();
		updateBuddyList();
		objHandler.postDelayed(loopUpdateList, 15000);

		bdyp_lv_buddyList.setOnItemClickListener(handleBuddyListView);
		
	}

	@Override
	public void onDestroy(){
		Intent i = new Intent(BuddyPage.this, UpdateLocationService.class);
		stopService(i);
		Log.d("Debug","Service UpdateLocationService stoped.");
		// Update User State
		String updateStatePage = getString(R.string.url_updateState);
		UpdateStateRequest usr = new UpdateStateRequest(updateStatePage);
		usr.updateState(userid,0);
		super.onDestroy();
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
		// param 1 : group id , param 2:itemId, param 3:item order, param 4:item
		// name
		menu.add(0, 0, 0, R.string.lbl_addBuddy);
		menu.add(0, 1, 1, R.string.lbl_createGroup);
		return super.onCreateOptionsMenu(menu);
	}
	
	// Handle Menu Item onClick Event
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case 0:
			showAddBuddyDialog();
			break;
		case 1:
			showCreateGroupDialog();
			break;
		}
		return true;
	}

	/*
	 *  ===============================================	 *
	 *  All method to perform action is below this line	 *
	 *  ===============================================	 *
	 */
	
	private void performAddBuddy(){
		String email = abdy_et_email.getText().toString();
		int buddyid = 0;

		// Declare http objects
		String getBuddyIdPage = getString(R.string.url_getBuddyID);
		Log.d("DEBUGING", "email = " + email);

		GetBuddyIdRequest gbir = new GetBuddyIdRequest(getBuddyIdPage);
		buddyid = gbir.getBuddyId(email);

		// Declare http objects
		int result = 0;
		String addBuddyPage = getString(R.string.url_addBuddy);

		AddBuddyRequest abr = new AddBuddyRequest(addBuddyPage);
		result = abr.addBuddy(userid,buddyid);

		updateBuddyList();
	}
	
	private void performDeleteBuddy(){
		int result = 0;
		int buddyid = selectedBuddy.getBuddyid();

		// Declare http objects
		String deleteBuddyPage = getString(R.string.url_delBuddyPage);

		DeleteBuddyRequest dbr = new DeleteBuddyRequest(deleteBuddyPage);
		result = dbr.deleteBuddy(userid,buddyid);

		if (result == 1) {
			// Delete successful
			Toast.makeText(BuddyPage.this, "Delete successful.",
					Toast.LENGTH_LONG).show();
		} else {
			// Delete fail
			Toast.makeText(BuddyPage.this, "Delete fail", Toast.LENGTH_LONG)
					.show();
		}
		updateBuddyList();
	}
	
	private void performCreateGroup(){
		if (cgrp_et_title.getText().length() > 0
				&& cgrp_et_description.getText().length() > 0) {

			String title = cgrp_et_title.getText().toString();
			String description = cgrp_et_description.getText()
					.toString();
			int result = 0;

			// Declare http objects
			String createGroupPage = getString(R.string.url_createGroupPage);
			Log.d("Debug", "Title = " + title + " , Description = "
					+ description);
			
			CreateGroupRequest cgr = new CreateGroupRequest(createGroupPage);
			result = cgr.createGroup(userid,title,description);
			
			Toast.makeText(BuddyPage.this, "Group created.",
					Toast.LENGTH_LONG).show();

		} else {
			Toast.makeText(BuddyPage.this, "Please enter all field.",
					Toast.LENGTH_LONG).show();

		}
		getGroupList();
	}
	
	// Refresh Buddy List
	private void updateBuddyList() {

		BuddyAdapter adapter;

		// Declare http objects
		String getBuddy = getString(R.string.url_getBuddy);

		GetBuddyRequest gbr = new GetBuddyRequest(getBuddy);
		buddies = gbr.sendRequest(userid);

		adapter = new BuddyAdapter(this, buddies, groups);

		// Add to ListView
		bdyp_lv_buddyList.setAdapter(adapter);

	}
	
	// Regresh Group List
	private void getGroupList() {

		// Declare http objects
		String getGroup = getString(R.string.url_getGroup);

		GetGroupRequest ggr = new GetGroupRequest(getGroup);
		groups = ggr.sendRequest(userid);

	}
	
	/*
	 *  ==============================================	*
	 *  All method to call a dialog is below this line	*
	 *  ==============================================	*
	 */

	private void showBuddyAlertMenu(){
		String[] menu;
		// If Buddy is Online
		if (selectedBuddy.getState() == 1) {
			menu = getResources()
					.getStringArray(R.array.mnu_buddy_item);
		} else {
			// If Buddy is Offline
			menu = new String[2];
			for (int i = 0; i < 2; i++) {
				menu[i] = getResources().getStringArray(
						R.array.mnu_buddy_item)[i];
			}
		}

		new AlertDialog.Builder(BuddyPage.this)
				.setTitle("What you want to do?")
				.setItems(menu, handleBuddyAlertMenu)
				.setPositiveButton(getString(R.string.lbl_cancel), null)
				.show();
	}
	
	private void showGroupAlertMenu(){
		String[] menu = getResources().getStringArray(
				R.array.mnu_group_item);

		new AlertDialog.Builder(BuddyPage.this)
				.setTitle("What you want to do?")
				.setItems(menu, handleGroupAlertMenu)
				.setPositiveButton(getString(R.string.lbl_cancel), null)
				.show();
	}
	
	private void showAddBuddyDialog(){
		LayoutInflater factory = LayoutInflater.from(BuddyPage.this);
		View addBuddyView = factory.inflate(R.layout.add_buddy_dialog, null);
		abdy_et_email = (EditText) addBuddyView
				.findViewById(R.id.abdy_et_email);

		AlertDialog addBuddyDialog = new AlertDialog.Builder(BuddyPage.this)
				.create();
		addBuddyDialog.setView(addBuddyView);
		addBuddyDialog.setButton(getString(R.string.lbl_addBuddy),
				handleAddBuddyButton);

		addBuddyDialog.show();
	}
	
	private void showCreateGroupDialog(){
		LayoutInflater factory = LayoutInflater.from(BuddyPage.this);
		View createGroupView = factory.inflate(R.layout.cgrp, null);

		cgrp_et_title = (EditText) createGroupView
				.findViewById(R.id.cgrp_et_title);
		cgrp_et_description = (EditText) createGroupView
				.findViewById(R.id.cgrp_et_description);

		AlertDialog createGroupDialog = new AlertDialog.Builder(BuddyPage.this)
				.create();
		createGroupDialog.setView(createGroupView);
		createGroupDialog.setButton(getString(R.string.lbl_createGroup),
				handleCreateGroupButton);

		createGroupDialog.show();
	}

	private void showDeleteBuddyDialog() {
		Builder deleteBuddyDialog = new AlertDialog.Builder(BuddyPage.this)
				.setTitle(R.string.lbl_delBuddy)
				.setMessage(getString(R.string.lbl_delBuddy) + "?")
				.setPositiveButton(R.string.lbl_delBuddy, handleDeleteBuddyButton)
				.setNegativeButton(R.string.lbl_cancel, null);
		deleteBuddyDialog.show();
	}

	private void showInviteGroupDialog() {
		// Put All Group's Name into String Array
		String[] groupString = new String[groups.size()];
		for (int i = 0; i < groups.size(); i++) {
			groupString[i] = groups.get(i).getTitle();
		}

		// Listener Handle Invite Group Dialog
		new AlertDialog.Builder(BuddyPage.this).setTitle("Select a group")
				.setItems(groupString, handleInviteGroupList)
				.setPositiveButton(getString(R.string.lbl_cancel), null).show();
	}

	/*
	 *  ===============================	*
	 *  All Listener is below this line	*
	 *  ===============================	*
	 */

	private OnItemClickListener handleBuddyListView = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> l, View v, int position, long id) {

			// If buddy selected
			if (position < buddies.size()) {
				selectedBuddy = buddies.get(position);
				Log.d("Debug",
						"Selected Buddy ID : " + selectedBuddy.getBuddyid());

				showBuddyAlertMenu();
			} else {
				// If group selected
				selectedGroup = groups.get(position - buddies.size());

				Log.d("bdyp_Debug",
						"Selected Group ID : " + selectedGroup.getGroupid());
				showGroupAlertMenu();
				
			}
		}
	};

	// Listener Handling Alert Menu
	private OnClickListener handleBuddyAlertMenu = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			if (which == 0) {
				// handle delete buddy
				showDeleteBuddyDialog();
			} else if (which == 1) {
				// handle invite buddy to group
				showInviteGroupDialog();
			} else if (which == 2) {
				// handle show buddy in map
				double[] lng = {114.155502};
				double[] lat = {22.241994};

				Log.d("Debug", "lat = " + lat[0] + " lng = " + lng[0]);

				Bundle bundle = new Bundle();
				bundle.putDoubleArray("lat", lat);
				bundle.putDoubleArray("lng", lng);

				Intent i = new Intent();
				i.setClass(BuddyPage.this, CreateSchedulePage.class);
				i.putExtras(bundle);
				startActivity(i);
			}
		}
	};

	// Listener handling alert menu onClick event
	private OnClickListener handleGroupAlertMenu = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			if (which == 0) {
				// handle View Group Member
				Bundle bundle = new Bundle();
				bundle.putInt("groupid", selectedGroup.getGroupid());

				Intent i = new Intent();
				i.setClass(BuddyPage.this, GroupPage.class);
				i.putExtras(bundle);
				startActivity(i);
			} else if (which == 1) {
				// handle Show Group Member in Map

			}
		}
	};
	
	// Listener Handling Group Menu OnClick Event
	private OnClickListener handleInviteGroupList = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			selectedGroup = groups.get(which);
			Log.d("bdyp_Debug", "Selected User : " + selectedBuddy.getName()
					+ " Selected Group : " + selectedGroup.getTitle());

			// Declare http objects
			String inviteGroup = getString(R.string.url_inviteGroupPage);

			int result = 0;
			int buddyid = selectedBuddy.getBuddyid();
			int groupid = selectedGroup.getGroupid();

			InviteGroupRequest igr = new InviteGroupRequest(inviteGroup);
			result = igr.inviteGroup(buddyid, groupid);
		}
	};

	private OnClickListener handleCreateGroupButton = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {

			performCreateGroup();
		}
	};
	
	private OnClickListener handleAddBuddyButton = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			performAddBuddy();
		}
	};
	
	private OnClickListener handleDeleteBuddyButton = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			performDeleteBuddy();
		}
	};
}
